"""
MCP上下文服务

提供上下文管理的业务逻辑层
"""

from typing import Dict, Any, Optional, List
from sqlalchemy.orm import Session
from app.models.mcp_context import MCPContext
from app.models.mcp_session import MCPSession
from app.core.mcp.context_manager import MCPContextManager
from app.core.logging_config import app_logger


class MCPContextService:
    """MCP上下文服务类"""
    
    def __init__(self, db: Session, redis_client: Optional[Any] = None):
        """
        初始化上下文服务
        
        Args:
            db: 数据库会话
            redis_client: Redis客户端（可选）
        """
        self.db = db
        self.redis = redis_client
        self.context_manager = MCPContextManager(db=db, redis_client=redis_client)
        self.logger = app_logger
    
    async def create_context(
        self,
        session_id: str,
        context_data: Dict[str, Any],
        context_type: str = "user",
        context_metadata: Optional[Dict[str, Any]] = None,
        model_id: Optional[str] = None
    ) -> MCPContext:
        """
        创建上下文
        
        Args:
            session_id: MCP会话ID
            context_data: 上下文数据
            context_type: 上下文类型
            context_metadata: 元数据
            model_id: 模型ID
            
        Returns:
            MCPContext: 创建的上下文对象
        """
        return self.context_manager.create_context(
            session_id=session_id,
            context_data=context_data,
            context_type=context_type,
            context_metadata=context_metadata,
            model_id=model_id
        )
    
    async def update_context(
        self,
        context_id: int,
        context_data: Dict[str, Any],
        increment_version: bool = True
    ) -> MCPContext:
        """更新上下文"""
        return self.context_manager.update_context(
            context_id=context_id,
            context_data=context_data,
            increment_version=increment_version
        )
    
    async def get_context(self, context_id: int) -> Optional[MCPContext]:
        """获取上下文"""
        return self.context_manager.get_context(context_id=context_id)
    
    async def get_session_contexts(
        self,
        session_id: str,
        context_type: Optional[str] = None,
        limit: int = 50
    ) -> List[MCPContext]:
        """获取会话的所有上下文"""
        return self.context_manager.get_session_contexts(
            session_id=session_id,
            context_type=context_type,
            limit=limit
        )
    
    async def delete_context(self, context_id: int) -> bool:
        """删除上下文"""
        return self.context_manager.delete_context(context_id=context_id)
    
    async def delete_session_contexts(self, session_id: str) -> int:
        """删除会话的所有上下文"""
        return self.context_manager.delete_session_contexts(session_id=session_id)

